package com.ly.aicode.core;

import cn.hutool.core.util.ObjUtil;
import com.ly.aicode.ai.AiCodeGeneratorService;
import com.ly.aicode.ai.model.HtmlCodeResult;
import com.ly.aicode.ai.model.MultiFileCodeResult;
import com.ly.aicode.core.parse.CodeParseExecutor;
import com.ly.aicode.core.saver.CodeFileSaverExecutor;
import com.ly.aicode.exception.BusinessException;
import com.ly.aicode.exception.ErrorCode;
import com.ly.aicode.model.enums.CodeGenTypeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.io.File;

/**
 * @author luyi
 * @date 2025/11/8 0:33
 */
@Slf4j
@Service
public class AiCodeGeneratorFacade {
    @Resource
    private AiCodeGeneratorService aiCodeGeneratorService;

    /**
     * 生成并保存代码文件
     *
     * @param userMessage
     * @param codeGenType
     * @return
     */
    public File generatorAndSaveCode(String userMessage, CodeGenTypeEnum codeGenType) {
        if (ObjUtil.isEmpty(codeGenType)) throw new BusinessException(ErrorCode.PARAMS_ERROR, "代码生成类型不能为空");
        return switch (codeGenType) {
            case HTML -> {
                HtmlCodeResult htmlCodeResult = aiCodeGeneratorService.generateHtmlCode(userMessage);
                yield CodeFileSaverExecutor.executeSave(htmlCodeResult, codeGenType);
            }
            case MULTI_FILE -> {
                MultiFileCodeResult multiFileCodeResult = aiCodeGeneratorService.generateMultiFileCode(userMessage);
                yield CodeFileSaverExecutor.executeSave(multiFileCodeResult, codeGenType);
            }
        };
    }

    /**
     * 生成并保存代码流式
     *
     * @param userMessage
     * @param codeGenType
     * @return
     */
    public Flux<String> generatorAndSaveCodeStream(String userMessage, CodeGenTypeEnum codeGenType) {
        if (ObjUtil.isEmpty(codeGenType)) throw new BusinessException(ErrorCode.PARAMS_ERROR, "代码生成类型不能为空");
        return switch (codeGenType) {
            case HTML -> {
                Flux<String> stringFlux = aiCodeGeneratorService.generateHtmlCodeStream(userMessage);
                yield this.processSteamCode(stringFlux, codeGenType);
            }
            case MULTI_FILE -> {
                Flux<String> stringFlux = aiCodeGeneratorService.generateMultiFileCodeStream(userMessage);
                yield this.processSteamCode(stringFlux, codeGenType);
            }
            default -> throw new BusinessException(ErrorCode.PARAMS_ERROR, "代码生成类型错误");
        };
    }

    /**
     * 通用流式处理代码逻辑
     *
     * @param result
     * @param genTypeEnum
     * @return
     */
    private Flux<String> processSteamCode(Flux<String> result, CodeGenTypeEnum genTypeEnum) {
        StringBuilder stringBuilder = new StringBuilder();
        return result
                .doOnNext(stringBuilder::append)
                .doOnComplete(() -> {
                    try {
                        Object object = CodeParseExecutor.codeParseExecute(stringBuilder.toString(), genTypeEnum);
                        File file = CodeFileSaverExecutor.executeSave(object, genTypeEnum);
                        log.info("文件保存路径:{}", file.getAbsolutePath());
                    } catch (Exception e) {
                        log.error("文件保存失败:{}", e.getMessage());
                    }
                });
    }
}
